import React, { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import useUserStore from '../../stores/userStore';
import { LoadingSpinner } from '../LoadingSpinner';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const isLoggedIn = useUserStore((state) => state.isLoggedIn);
  const loading = useUserStore((state) => state.loading);
  const initializeAuth = useUserStore((state) => state.initializeAuth);
  const location = useLocation();
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    // 应用启动时初始化认证状态
    const init = async () => {
      await initializeAuth();
      setIsInitialized(true);
    };
    
    init();
  }, [initializeAuth]);

  // 如果还在初始化认证状态，显示加载中
  if (!isInitialized || loading) {
    return <LoadingSpinner message="验证登录状态中..." />;
  }

  if (!isLoggedIn) {
    // 保存当前路径，登录后可以重定向回来
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return <>{children}</>;
};

export default ProtectedRoute;
